package com.lyr.udpdemo;

import java.io.*;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Scanner;

public class ClientThread extends Thread{

    private DatagramSocket socket;

    public ClientThread() {

        super("顾客：");
    }

    @Override
    public void run() {

        try {
            // 初始化客户端DatagramSocket
            socket = new DatagramSocket();
            byte[] bt=new byte[1024];
            DatagramPacket sdp=new DatagramPacket(bt,bt.length);

            while (true) {
                ///////////////////////////////// 发送消息到服务器//////////////////

                // 输出内容到网络，发送到服务器端
                Scanner sc=new Scanner(System.in);
                String strClientMsg=Thread.currentThread().getName();
                strClientMsg+=sc.next();
                // 将需要发送的消息打包到数据包中
                DatagramPacket cdp=new DatagramPacket(strClientMsg.getBytes(),0,
                        strClientMsg.getBytes().length,new InetSocketAddress("localhost",9999));
                socket.send(cdp);

                ///////////////////////////////// 接收服务器的消息//////////////////

                socket.receive(sdp);
                int len=cdp.getLength();
                String cSendSmg=new String(bt,0,len);
                System.out.println(cSendSmg);
            }
        } catch(IOException e){
                e.printStackTrace();
        }
    }
}
